import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';

/// 获取设备相关信息工具类
class DeviceUtil {

  /// 是否请求过权限弹框
  static const String _deviceKey = "device_key";

  /// 获取设备类型相关信息
  static DeviceInfoPlugin? _deviceInfoPlugin;

  /// ios相关设备信息
  static IosDeviceInfo? _iosDeviceInfo;

  /// 安卓相关设备信息
  static AndroidDeviceInfo? _androidDeviceInfo;

  /// 保存收集信息同意
  static void _saveDeviceKey() {
    HiCache.getInstance().setBool(_deviceKey, true);
  }

  static bool? getDeviceKey() {
    var value = HiCache.getInstance().get(_deviceKey);
    if (value != null) {
      return value;
    }
    return null;
  }

  /// 初始化方法
  static void deviceInit() {
    _saveDeviceKey();
    _deviceInfoPlugin ??= DeviceInfoPlugin();
  }

  /// 获取设备类型
  static String getDeviceType() {
    if (Platform.isIOS) {
      return "ios";
    } else if (Platform.isAndroid) {
      return "android";
    }
    return "";
  }

  /// 获取ios相关设备信息方法
  static Future<IosDeviceInfo> getIosDeviceInfo() async {
    if (_iosDeviceInfo != null) {
      return _iosDeviceInfo!;
    } else {
      _iosDeviceInfo = await _deviceInfoPlugin!.iosInfo;
      return _iosDeviceInfo!;
    }
  }

  /// 获取安卓相关信息方法
  static Future<AndroidDeviceInfo> getAndroidDeviceInfo() async {
    if (_androidDeviceInfo != null) {
      return _androidDeviceInfo!;
    } else {
      _androidDeviceInfo = await _deviceInfoPlugin!.androidInfo;
      return _androidDeviceInfo!;
    }
  }

  /// 获取设备相关id
  static Future<String> getDeviceId() async {
    if (Platform.isIOS) {
      var iosDeviceInfo = await getIosDeviceInfo();
      return iosDeviceInfo.identifierForVendor!;
    } else if (Platform.isAndroid) {
      var androidDeviceInfo = await getAndroidDeviceInfo();
      return androidDeviceInfo.fingerprint;
    }
    return "";
  }
}
